from django.shortcuts import render

from . import tasks as TASKS
from .serializers import *
from PlaceManager.tasks import has_pid_from_idcode
from datetime import datetime, date
import logging

logger = logging.getLogger(__name__)
# Create your views here.


class HasWorkMemberListViewSet(viewsets.ModelViewSet):
    __title__ = "查询当前终端的会员标识"
    __group__ = "数据接口"
    __info__ = {"post": "场所会员数据查询"}
    __doc__ = """
    create:
    <h4>场所会员数据查询</h4>
        查询当前终端的会员标识
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = HasWorkMemberListSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        pid = has_pid_from_idcode("凡商编码", serializer.data.get("barid"))
        if not pid:raise serializers.ValidationError("查询门店失败")        
        try:
            place = AllinpayPlaceList.objects.get(
                id=pid, status=1
            )
            line = FsygLineinfoList.objects.get(
                message_type="machine_up",
                wb_id=serializer.data.get("barid"),
                computer_name=serializer.data.get("host"),
            )
            vip = line.card_id
        except AllinpayPlaceList.DoesNotExist as err:
            raise serializers.ValidationError("查询场所信息异常")
        except FsygBuysinfoList.DoesNotExist as err:
            raise serializers.ValidationError("查询上机信息异常")
        except BaseException as err:
            raise serializers.ValidationError("查询失败")

        return Response({"rescode": 200, "resmsg": vip})


class MoniterHasWorkViewSet(viewsets.ModelViewSet):
    __title__ = "场所大屏登录"
    __group__ = "数据接口"
    __info__ = {"post": "POST查询上机数据"}
    __doc__ = """
    create:
    <h4>场所大屏登录</h4>
        返回全场工作站状态
        "rescode": 200, 状态码
        "pulsar": {
            pulsar.url: 消息队列服务器
            pulsar.topic: 订阅主题             
        },
        "resmsg": [
            {
                "member": "{'hash': '95283DFA18F73F60BF3DAAC09FAD6A0D', 'registtime': '2023-09-08 16:08:45', 'lasttime': '2023-09-12 09:31:20.626845', 'level': '会员用户', 'overage': '435.9'}", 
                "currenttime": "2023-09-12 09:31:20", 
                "ipaddr": "192.168.0.63", 
                "group": "Area3", 
                "localhost": "PC063", 
                "Count": "{'timelong': 11193, 'dolong': 11194, 'money': 0, 'domoney': 11194, 'week': 0}", 
                "status": "1"
            }        
        ],
        "post":  [
            {
                "id": 1027, 
                "basename": "董玉霞", 
                "nicename": "小玉", 
                "icon": "/static/upload/173278645131.jpg"
            }
        ], 
        "work": [
            {
                "id": 4131, 
                "title": "【天】主持班会", 
                "outtype": null, 
                "onstaff": 1005, 
                "over": "08:30:00", 
                "staff": {
                    "id": 1005, 
                    "basename": "胡炎孙", 
                    "nicename": "瓜哥"
                }, 
                "submit": ""
            }]        
      
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = HasWorkSerializer
    queryset = AllinpayPlaceList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()

        data = serializer.data.copy()
        barid = data.pop("barid")

        pid = has_pid_from_idcode("凡商编码", barid)
        if not pid:raise serializers.ValidationError("查询门店失败")
        try:
            pid = AllinpayPlaceList.objects.get(id=pid, status=1)
        except BaseException as err:
            raise serializers.ValidationError({"pid": "该场所未注册或已停用"})
        else:
            # Topic = "persistent://public/workReport/map--1000001";
            pulsar = {
                "url": "pulsar://api.yisbar.com:26650",
                "topic": f'non-persistent://public/workReport/{data.get("types")}--{pid.id}',
            }
            if pid.id in [1000001, 1000000]:
                return Response(
                    {
                        "rescode": 200,
                        "pulsar": pulsar,
                        "websocket": f"wss://api.yisbar.com/wschat/{pid.id}/",
                        "resmsg": self.make_data(pid.id),
                        "post": self.hasPost(pid.id),
                        "work": self.hasItem(pid.id),
                    }
                )
            else:
                # 重新区域终端列表
                r = FsygPchardList.objects.filter(pid=pid.id).values_list(
                    "name", flat=True
                )
                sess = [
                    REDIS.redis_hash_has("workStatus", f"{pid.id}--{i}")
                    for i in list(r)
                ]
                # 去除None
                # sess = REDIS.clear_dict(sess)
                # key = f"{pid.id}--*"
                # res = REDIS.redis_key_find("workStatus", key)
                # sess = [REDIS.redis_hash_has("workStatus", i) for i in res]
                return Response(
                    {
                        "rescode": 200,
                        "pulsar": pulsar,
                        "websocket": f"wss://api.yisbar.com/wschat/{pid.id}/",
                        "resmsg": sess,
                        "post": self.hasPost(pid.id),
                        "work": self.hasItem(pid.id),
                    }
                )

    def hasItem(self, pid):
        """查询当日工作项事务"""
        r = AllinpayPlaceworkitemList.objects.filter(
            pid=pid, currentdate=date.today()
        ).values("id", "title", "outtype", "onstaff", "over")
        res = list(r)
        for i in res:
            i["staff"] = self.hasStaff(i["onstaff"])
            i["submit"] = self.hasSubmit(i["id"])
        return res

    def hasSubmit(self, wid):
        """查询提交时间"""
        try:
            r = AllinpayPlaceworkitemSubmit.objects.get(wid=wid)
        except BaseException as err:
            return ""
        else:
            return r.currentime

    def hasStaff(self, sid):
        try:
            s = AllinpayStaffList.objects.get(id=sid)
        except BaseException as err:
            return None
        else:
            return {"id": s.id, "basename": s.basename, "nicename": s.nicename}

    def hasPost(self, pid):
        """查询在岗员工"""
        r = AllinpayPlacestaffPost.objects.filter(status=1).values_list("id", flat=True)
        b = AllinpayPlacestaffList.objects.filter(
            status=1, id__in=list(r), pid=pid
        ).values_list("sid", flat=True)
        res = AllinpayStaffList.objects.filter(id__in=list(b)).values(
            "id", "basename", "nicename", "icon"
        )
        return res

    def toName(self, hao):
        x = str(hao)
        if len(x) == 1:
            return f"00{x}"
        elif len(x) == 2:
            return f"0{x}"
        else:
            return f"{x}"

    def make_data(self, pid):
        works = []
        for i in range(1, 150):
            works.append(
                {
                    "status": f"{random.choice(range(4))}",
                    "localhost": f"{self.toName(i)}",
                    "group": "终端区域",
                    "ipaddr": f"192.168.0.{i}",
                    "mask": "255.255.255.0",
                    "gateway": "192.168.0.254",
                    "mac": "ff:ff:ff:ff:ff:ff",
                    "currenttime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    "member": {
                        "name": "姓名",
                        "code": "身份证",
                        "hash": "身份标识",
                        "phone": "电话",
                        "birthday": "生日",
                        "gender": f"{random.choice(range(2))}",
                        "openid": "openid",
                        "registtime": "注册时间",
                        "lasttime": "上次登录",
                        "level": f"{random.choice(range(1,7))}",
                        "overage": f"{random.choice(range(1000))}",
                        "reward": f"{random.choice(range(1000))}",
                        "integral": f"{random.choice(range(1000))}",
                    },
                    "games": [
                        {
                            "name": "lol",
                            "info": "大区等信息",
                            "online": ["023", "013", "015"],
                        },
                        {
                            "name": "csgo",
                            "info": "大区等信息",
                            "online": ["023", "013", "015"],
                        },
                    ],
                    "Friends": [1, 2, 3, 4, 5],
                    "count": 0,
                }
            )
        return works


class MoniterOnlineWorkingStateViewSet(viewsets.ModelViewSet):
    __title__ = "工作站上线"
    __group__ = "数据接口"
    __info__ = {"post": "工作站上线"}
    __doc__ = """
    create:
    <h4>工作站上线</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = MoniterOnlineWorkingStateSerializer
    queryset = FsygMemberList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # print(serializer.data)
        # 检查场所
        pid = has_pid_from_idcode("凡商编码", serializer.data.get("barid"))
        if not pid:raise serializers.ValidationError("查询门店失败")        
        try:
            place = AllinpayPlaceList.objects.get(
                status=1, id=pid
            )
        except AllinpayPlaceList.DoesNotExist as err:
            raise serializers.ValidationError("该场所未注册")
        # 检查会员
        v, faq = FsygMemberList.objects.update_or_create(
            defaults={"currentdate": timezone.now()},
            wb_id=serializer.data.get("barid"),
            codeid=serializer.data.get("vhash"),
        )
        # 创建数据
        dbs = {
            "status": 1,
            "localhost": serializer.data.get("host"),
            "group": "终端区域",
            "ipaddr": f"192.168.0.1",
            "mask": "255.255.255.0",
            "gateway": "192.168.0.254",
            "mac": "ff:ff:ff:ff:ff:ff",
            "currenttime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            "member": {
                "name": v.bashname,
                "code": "身份证",
                "hash": v.codeid,
                "phone": "电话",
                "birthday": v.birthday,
                "gender": v.gender,
                "openid": "openid",
                "registtime": "注册时间",
                "lasttime": "上次登录",
                "level": f"{random.choice(range(1,7))}",
                "overage": f"{random.choice(range(1000))}",
                "reward": f"{random.choice(range(1000))}",
                "integral": f"{random.choice(range(1000))}",
            },
        }

        # 去除 None
        dbs = REDIS.clear_dict(dbs)
        # 写入缓存数据
        key = f'{place.id}--{serializer.data.get("host")}'
        REDIS.redis_hash_set("workStatus", key, dbs)
        # 发送消息队列pulsar
        r = TASKS.doMoniterPulsarScreen.apply_async((f"{place.id}", dbs))
        return Response(
            {"rescode": 200, "resmsg": serializer.data, "taskID": r.task_id}
        )


class MoniterUpdateWorkingStateViewSet(viewsets.ModelViewSet):
    __title__ = "工作站状态切换"
    __group__ = "数据接口"
    __info__ = {"post": "工作站状态切换"}
    __doc__ = """
    create:
    <h4>工作站状态切换</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = MoniterUpdateWorkingStateSerializer
    queryset = FsygMemberList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # print(serializer.data)

        # 检查场所
        pid = has_pid_from_idcode("凡商编码", serializer.data.get("barid"))
        if not pid:raise serializers.ValidationError("查询门店失败")        
        try:
            place = AllinpayPlaceList.objects.get(
                status=1, id=pid
            )
        except AllinpayPlaceList.DoesNotExist as err:
            raise serializers.ValidationError("该场所未注册")

        infos = ["终端维修中", "会员上机", "会员下机", "终端待机中"]

        # 创建数据
        dbs = {
            "status": int(serializer.data.get("status")),  # 终端状态 0维修，1上机中，2待清洁，3待机中
            "localhost": serializer.data.get("host"),  # 终端机号
        }
        # 去除 None
        dbs = REDIS.clear_dict(dbs)
        # 写入缓存数据
        key = f'{place.id}--{serializer.data.get("host")}'
        REDIS.redis_hash_set("workStatus", key, dbs)

        # 发送消息队列pulsar
        r = TASKS.doMoniterPulsarScreen.apply_async((f"{place.id}", dbs))
        return Response(
            {"rescode": 200, "resmsg": serializer.data, "taskID": r.task_id}
        )


class MoniterUpdateWorkingEventViewSet(viewsets.ModelViewSet):
    __title__ = "工作站事件"
    __group__ = "数据接口"
    __info__ = {"post": "工作站事件"}
    __doc__ = """
    create:
    <h4>工作站事件</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    # serializer_class = MoniterUpdateWorkingEventSerializer
    serializer_class = NoneSerializer
    queryset = FsygMemberList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        # 发送消息队列pulsar
        r = TASKS.doWorkItemEvent(27)
        return Response({"rescode": 200, "resmsg": serializer.data})


class MoniterUpdateGoodEventViewSet(viewsets.ModelViewSet):
    __title__ = "上报打赏点赞数据"
    __group__ = "数据接口"
    __info__ = {"post": "上报打赏点赞数据"}
    __doc__ = """
    create:
    <h4>上报打赏点赞数据</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class MoniterUpdateGamesEventViewSet(viewsets.ModelViewSet):
    __title__ = "上报游戏登录数据"
    __group__ = "数据接口"
    __info__ = {"post": "上报游戏登录数据"}
    __doc__ = """
    create:
    <h4>上报游戏登录数据</h4>
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = MoniterUpdateGamesStateSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        pid = has_pid_from_idcode("凡商编码", serializer.data.get("barid"))
        if not pid:raise serializers.ValidationError("查询门店失败")        
        try:
            place = AllinpayPlaceList.objects.get(
                id=pid, status=1
            )
        except AllinpayPlaceList.DoesNotExist as err:
            raise serializers.ValidationError("查找场所失败")
        data = serializer.data.copy()
        # 异步处理
        r = TASKS.doGamesEvent.apply_async((place.id, data))
        return Response({"rescode": 200, "resmsg": r.task_id})


class TestSendMessageViewSet(viewsets.ModelViewSet):
    __title__ = "自费消息发送测试"
    __group__ = "数据接口"
    __info__ = {"put": "创建自费消息发送测试"}
    __doc__ = """
    update:
    <h4>创建自费消息发送测试</h4>
    """
    http_method_names = ["put"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = TestSendMessageNoneSerializer
    queryset = None

    def update(self, request, *args, **kwargs):
        pid = kwargs.get("pk")
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        r = TASKS.doMoniterPulsarScreen.apply_async((pid, serializer.data))
        return Response({"rescode": 200, "resmsg": r.task_id})


# 检查视图
filter_views(globals())
